<template>

  <el-dialog
    :visible="visible"
    center
    :show-close="false"
    width="480px"
  >
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{$t('sys.add_interval')}}</span>
        <span
          class="el-icon-close g9 f26 poi"
          @click="handleCancel"
        ></span>
      </div>
    </div>

    <el-form :form="form" ref="form" label-width="80px" >
      <el-form-item :label="$t('sys.time')" prop="time">
        <el-form-item style="display: inline-block; margin-right: 12px;">
          <el-input-number v-model="form.time" :min="1" :max="maxTime" :precision="0" @blur="onBlurTime" />
        </el-form-item>
        <el-form-item :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <el-select v-model="unit" style="width: 100%">
            <el-option value="day" :label="$t('sys.days')"></el-option>
            <el-option value="hour" :label="$t('sys.hours')"></el-option>
            <el-option value="min" :label="$t('sys.minutes')"></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
    </el-form>
    <div slot="footer" class="tr">
      <el-button @click="handleCancel">{{$t('sys.cancel')}}</el-button>
      <el-button type="primary" @click="handleSubmit">{{$t('sys.confirm')}}</el-button>
    </div>

  </el-dialog>
</template>

<script>
export default {
  name: 'TimeForm',
  data() {
    return {
      tempId: 0,
      visible: false,
      form: {},
      unit: 'min'
    }
  },
  computed: {
    maxTime() {
      switch (this.unit) {
      case 'min':
        return 60 * 24 * 360
      case 'hour':
        return 24 * 360
      case 'day':
        return 360
      }
    }
  },
  methods: {
    show(values) {
      this.visible = true
      this.tempId = values.tempId
      this.$nextTick(() => {
        if (values.intervalTime) {
          const temp = this.fitUnit(values.intervalTime)
          this.form = {
            time: temp.val
          }
          this.unit = temp.unit
        } else {
          this.resetForm()
        }
      })
    },

    fitUnit(min) {
      if (min % 1440 === 0) {
        return {
          val: min / 1440,
          unit: 'day'
        }
      } else if (min % 60 === 0) {
        return {
          val: min / 60,
          unit: 'hour'
        }
      } else {
        return {
          val: min,
          unit: 'min'
        }
      }
    },

    onBlurTime(e) {
      if (!e.target.value) {
        this.form.time = 1
      }
    },

    handleSubmit() {
      const { time } = this.form
      const intervalTime = time * (this.unit === 'day' ? 1440 : this.unit === 'hour' ? 60 : 1)
      this.$emit('ok', { tempId: this.tempId, intervalTime })
      this.handleCancel()
    },

    handleCancel() {
      this.resetForm()
      this.visible = false
    },

    resetForm() {
      this.form = { time: 1 }
    }
  }
}
</script>

<style></style>
